<?php

class CourseWorksController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = 'column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('admin','delete','create','update','view','index','free','requestsIndex','requestsConfirm','requestsConfirmed','requestsFinal'),
				'roles'=>array('professor',
                                               'administrator'
                                     ),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new CourseWorks;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CourseWorks']))
		{
			$model->attributes=$_POST['CourseWorks'];
                        $model->professor_id = Yii::app()->user->id;

                        $model->facultyid = Yii::app()->user->faculty_id;
                        $model->choosed = 0;
                        
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CourseWorks']))
		{
			$model->attributes=$_POST['CourseWorks'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
                // we only allow deletion via POST request
		if(Yii::app()->request->isPostRequest)
		{
                    if(isset($_GET['id'])) {
                        $requests = Requests::model()->deleteAll('coursework_id=:coursework_id', array(':coursework_id'=>$_GET['id']));
                        
                        $this->loadModel()->delete();
                    }
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists current professor topics with choosed=0
         * !! renders admin.php !!
	 */
	public function actionIndex()
	{
            $condition = 'professor_id ='.Yii::app()->user->id.' AND studentid IS NULL';
            $dataProvider = new CActiveDataProvider('CourseWorks', array(
                     'criteria'=>array(
                             'condition'=>$condition,
                     //       'with'=>array('courseWork'),
                     )
             )
                    );
            $this->render('admin',array(
                    'dataProvider'=>$dataProvider,
            ));
              
	}

        public function actionRequestsIndex()
	{
            
            $condition = 'courseWork.professor_id ='.Yii::app()->user->id.' AND archived=0 AND courseWork.studentid IS NULL';
            $dataProvider = new CActiveDataProvider('Requests', array(
                            'criteria'=>array(
                                'condition'=>$condition,
                                'with'=>array('courseWork'),
                                )
                )
                    );



      //      $dataProvider = new CActiveDataProvider('Requests');
            $this->render('requestsIndex',array(
                    'dataProvider'=>$dataProvider,
            ));
	}

        /*
         * Sets 'archived' to '1' of current Requests row & set '1' into 'choosed' row of CourseWorks
         */
        public function actionRequestsConfirm() {
            if (isset($_GET['id'])) {
                $request = Requests::model()->find('id=:id', array(':id'=>$_GET['id']));
                if($request !== null) {
                    $request->archived = '0';
                    $request->save();
                }
                
                    //set 'choosed' to '1'
                    $coursework = CourseWorks::model()->find('id=:id', array(':id'=>$request->courseWork_id));
                    if($coursework !== null) {
                        $coursework->choosed = '1';
                        $coursework->save();
                    } else {
                        echo 'ERROR! current courseWork did not find! "choosed" did not set to "1"';
                    }
                
            } else {
                echo 'ERROR! The "id" of the GET request is not specified!';
            }

            $this->redirect(array('requestsconfirmed'));
        }

            /**
	 * Shows confirmed by current professor topics.
	 */
        public function actionRequestsConfirmed() {

            $condition = 'courseWork.professor_id ='.Yii::app()->user->id.' AND courseWork.choosed=1 AND archived=0 AND courseWork.studentid IS NULL';
            $dataProvider = new CActiveDataProvider('Requests', array(
                            'criteria'=>array(
                                'condition'=>$condition,
                                'with'=>array('courseWork'),
                                )
                )
                    );

            $this->render('requestsconfirmed',array(
                    'dataProvider'=>$dataProvider,
            ));

        }
        /*
         * Set '0' to 'choosed' and '0' to 'archived'
         */
        public function actionFree()
	{
            if (isset($_GET['id'])) {
                $request = Requests::model()->find('id=:id', array(':id'=>$_GET['id']));
                if($request !== null) {
                    $request->archived = '0';

                }
                $request->save();
                    
                    $coursework = CourseWorks::model()->find('id=:id', array(':id'=>$request->courseWork_id));
                    if($coursework !== null) {
                        $coursework->choosed = '0';
                        $coursework->save();
                    } else {
                        echo 'ERROR! current courseWork did not find! "choosed" did not set to "0"';
                    }

            } else {
                echo 'ERROR! The "id" of the GET request is not specified!';
            }
            $this->redirect(array('courseWorks/index'));
	}

        /*
         * Shows final candidates
         */
        public function actionRequestsFinal() {
            $condition = 'courseWork.professor_id ='.Yii::app()->user->id.' AND courseWork.studentid IS NOT NULL';
            $dataProvider = new CActiveDataProvider('Requests', array(
                            'criteria'=>array(
                                'condition'=>$condition,
                                'with'=>array('courseWork','student'),
                                )
                )
                    );

            $this->render('requestsFinal',array(
                    'dataProvider'=>$dataProvider,
            ));
        }
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{

		$model=new CourseWorks('search');
		if(isset($_GET['CourseWorks']))
			$model->attributes=$_GET['CourseWorks'];

		$this->render('admin',array(
			'model'=>$model,
		));
         
         
    
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=CourseWorks::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='course-works-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
